package com.minxi.web.controller;

import com.minxi.web.javabean.UserInfo;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name= "ListServlet",urlPatterns="/list")
public class ListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection connection=null;
        PreparedStatement preparedStatement= null;
        //集合泛型
        List<UserInfo> list = new ArrayList<>();
        //2.请求数据库 JDBC
        try {
            //1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            String url = "jdbc:mysql://localhost:3306/student?serverTimezone=Asia/Shanghai";
            String user = "root";
            String pwd = "123456";
            connection = DriverManager.getConnection(url, user, pwd);
            //3.编辑SQL语句(预编译的执行对象)
            String sql = "select id,user_name,user_pwd,user_sex,user_phone from user_info;";
            //得到执行对象
            preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet= preparedStatement.executeQuery();
            //数据处理
            while (resultSet.next()){
                int id =resultSet.getInt("id");
                String userName = resultSet.getString("user_name");
                int userAge =resultSet.getInt("user_age");
                int userSex =resultSet.getInt("user_sex");
                String userPhone = resultSet.getString("user_phone");
                //封裝数据
                UserInfo userInfo= new UserInfo();

            }
            int rs = preparedStatement.executeUpdate();
            if (rs > 0) {

            } else {
                //如何将List放到页面上使用 HttpServletRequest Session(回话域)
                HttpServlet session1 = req.getSession();
                //KV 结构
                session1.setAttribute("userList",list);
                //跳转到指定页面
                resp.sendRedirect("jsp/home.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != preparedStatement) {
                    preparedStatement.close();
                }
                if (null !=connection){
                    connection.close();
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
